package com.qf.fmall01.service.impl;

import com.qf.fmall01.dao.OrderItemMapper;
import com.qf.fmall01.dao.OrdersMapper;
import com.qf.fmall01.dao.ProductSkuMapper;
import com.qf.fmall01.dao.ShoppingCartMapper;
import com.qf.fmall01.entity.OrderItem;
import com.qf.fmall01.entity.Orders;
import com.qf.fmall01.entity.ProductSku;
import com.qf.fmall01.entity.ShoppingCartVO;
import com.qf.fmall01.pay.wxpay.WxpayUtils;
import com.qf.fmall01.service.OrderService;
import com.qf.fmall01.service.ShoppingCartService;
import com.qf.fmall01.vo.ResStatus;
import com.qf.fmall01.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVO addOrder(String cids, Orders order) {

        ResultVO resultVO = new ResultVO();

        // 1. 保存订单的数
        // 1.1 校验库存
        ResultVO vo = shoppingCartService.listbycids(cids);
        List<ShoppingCartVO> shoppingCartVOList = (List<ShoppingCartVO>) vo.getData();

        StringBuilder stringBuilder = new StringBuilder();

        AtomicReference<Boolean> flag = new AtomicReference<>(true); // 是否超库存，true代表没超
        shoppingCartVOList.forEach((shoppingCartVO)->{
            stringBuilder.append(shoppingCartVO.getProductName()+",");
            if(Integer.valueOf(shoppingCartVO.getCartNum()) > shoppingCartVO.getStock()){
                flag.set(false);
            }
        });

        if (flag.get()){ // 没超库存

        // 1.2 保存订单的主表的信息
            String orderIdStr = UUID.randomUUID().toString().replaceAll("-", "");//  "xxxxxx-yyyyyy-uuuuu-xxxx"
            order.setOrderId(orderIdStr);
            order.setUntitled(stringBuilder.toString());
            order.setStatus("1"); // 待支付
            order.setCreateTime(new Date());
            ordersMapper.insert(order);

        // 1.3 保存订单明细表的信息
            shoppingCartVOList.forEach((shoppingCartVO)->{
                OrderItem orderItem = new OrderItem();
                orderItem.setItemId(UUID.randomUUID().toString().replaceAll("-", ""));
                orderItem.setOrderId(orderIdStr);
                orderItem.setProductId(shoppingCartVO.getProductId());
                orderItem.setProductName(shoppingCartVO.getProductName());
                orderItem.setProductImg(shoppingCartVO.getProductImg());
                orderItem.setSkuId(shoppingCartVO.getSkuId());
                orderItem.setSkuName(shoppingCartVO.getSkuName());
                orderItem.setProductPrice(shoppingCartVO.getProductPrice());
                orderItem.setBuyCounts(Integer.valueOf(shoppingCartVO.getCartNum()));
                // 计算总金额
                BigDecimal totalAmount = new BigDecimal(shoppingCartVO.getSellPrice() * Integer.valueOf(shoppingCartVO.getCartNum()));
                orderItem.setTotalAmount(totalAmount);
                orderItem.setBasketDate(new Date());
                orderItem.setBuyTime(new Date());
                orderItem.setIsComment(0);
                orderItemMapper.insert(orderItem);
            });
        // 1.4 减少商品套餐表里的库存
            shoppingCartVOList.forEach((shoppingCartVO)->{
                int newStockNum = shoppingCartVO.getStock() - Integer.valueOf(shoppingCartVO.getCartNum());
                ProductSku productSku = new ProductSku();
                productSku.setSkuId(shoppingCartVO.getSkuId());
                productSku.setStock(newStockNum);
                productSkuMapper.updateByPrimaryKeySelective(productSku);
            });

        // 1.5 删除购物车表中 对应的 cids的数据
            String[] cidsArr = cids.split(",");
            for (String cid : cidsArr) {
                shoppingCartMapper.deleteByPrimaryKey(cid);
            }
            // 2. 调用微信的支付接口，获取支付短链接字符串
            String payUrl="";
            try {
                payUrl = WxpayUtils.getPayUrl(orderIdStr);
            } catch (Exception e) {
                e.printStackTrace();
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("orderId",orderIdStr);
            map.put("payUrl",payUrl);
            resultVO.setCode(ResStatus.OK);
            resultVO.setMsg("success");
            resultVO.setData(map);
        }else{ // 超库存返回失败
            resultVO.setCode(ResStatus.NO);
            resultVO.setMsg("购物车的商品数据量超出了库存");
        }

        return resultVO;
    }


    @Override
    public ResultVO queryOrderStatus(String orderId) {
        ResultVO vo = new ResultVO();

        try {
            String s = WxpayUtils.queryOrder(orderId);
            if (s!=null && s.equals("SUCCESS")){
                vo.setCode(ResStatus.OK);
                vo.setMsg("success");
                vo.setData(ResStatus.WX_PAY_OK);  // 成功的标识
            }else{
                vo.setCode(ResStatus.NO);
                vo.setMsg("该订单尚未支付成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return vo;
    }
}
